from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel
from typing import List, Dict, Any, Generator, Iterator, Optional
from datetime import datetime
import copy
import time
from functools import wraps
from tools.jwt_tool import jwt_tool

# Pydantic模型定义
class CardResponse(BaseModel):
    id: int
    title: str
    description: str
    image: str
    location: str
    category: str
    type: Optional[str] = None
    views: int
    height: str

class CardListResponse(BaseModel):
    cards: List[CardResponse]
    total: int
    page: int
    page_size: int
    has_next: bool

# 装饰器：性能监控
def performance_monitor(func):
    """装饰器：监控函数执行时间"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"函数 {func.__name__} 执行时间: {end_time - start_time:.4f} 秒")
        return result
    return wrapper

# 装饰器：缓存结果
_cache = {}
def cache_result(expire_seconds: int = 300):
    """装饰器：缓存函数结果"""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            # 创建缓存键
            cache_key = f"{func.__name__}:{str(args)}:{str(kwargs)}"

            # 检查缓存
            if cache_key in _cache:
                cache_time, cached_result = _cache[cache_key]
                if time.time() - cache_time < expire_seconds:
                    print(f"使用缓存结果: {cache_key}")
                    return cached_result

            # 执行函数并缓存结果
            result = func(*args, **kwargs)
            _cache[cache_key] = (time.time(), result)
            return result
        return wrapper
    return decorator

# 装饰器：需要认证
def require_auth(func):
    """装饰器：验证JWT token"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        token = kwargs.get('token', '')
        if not token:
            raise HTTPException(status_code=401, detail="未授权访问")

        try:
            payload = jwt_tool.verify_token(token)
            kwargs['user_id'] = payload.get('user_id')
        except Exception as e:
            raise HTTPException(status_code=401, detail=f"Token验证失败: {str(e)}")

        return func(*args, **kwargs)
    return wrapper

# 工具类：数据处理
class DataProcessor:
    """数据处理工具类"""

    @staticmethod
    def card_generator(cards_data: List[Dict[str, Any]]) -> Generator[Dict[str, Any], None, None]:
        """生成器：逐个处理卡片数据"""
        for card in cards_data:
            # 深拷贝以避免修改原数据
            processed_card = copy.deepcopy(card)

            # 添加处理时间戳
            processed_card["processed_at"] = datetime.now().isoformat()

            # 模拟数据处理逻辑
            if "views" in processed_card:
                processed_card["views_formatted"] = f"{processed_card['views']:,}"

            yield processed_card

    @staticmethod
    def filter_cards_by_category(cards_data: List[Dict[str, Any]], category: str) -> Iterator[Dict[str, Any]]:
        """迭代器：按分类过滤卡片"""
        for card in cards_data:
            if card.get("category") == category:
                yield card

    @staticmethod
    def batch_process_cards(cards_data: List[Dict[str, Any]], batch_size: int = 10) -> Generator[List[Dict[str, Any]], None, None]:
        """生成器：批量处理卡片数据"""
        for i in range(0, len(cards_data), batch_size):
            batch = cards_data[i:i + batch_size]
            # 批量处理逻辑
            processed_batch = DataProcessor.process_batch(batch)
            yield processed_batch

    @staticmethod
    def process_batch(batch: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """静态方法：批量处理数据"""
        processed_batch = []
        for card in batch:
            # 深拷贝处理
            processed_card = copy.deepcopy(card)
            processed_card["batch_processed"] = True
            processed_batch.append(processed_card)
        return processed_batch

    @staticmethod
    def create_sample_cards() -> List[Dict[str, Any]]:
        """静态方法：创建示例卡片数据"""
        return [
            {
                "id": 1,
                "type": "路线",
                "image": "https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=400&h=200&fit=crop",
                "views": 813,
                "location": "苏州市",
                "title": "网师园|沧浪亭十全街漫游",
                "description": "网师园夜游偷师昆曲腔,沧浪亭漏窗框住宋朝光影 🌙",
                "category": "热门",
                "height": "short"
            },
            {
                "id": 2,
                "type": "景点",
                "image": "https://images.unsplash.com/photo-1540959733332-eab4deabeeaf?w=400&h=300&fit=crop",
                "views": 78,
                "location": "日本",
                "title": "长野新泫周游券深度游",
                "description": "玩转长野新泫:泡猴汤、访古寺、尝地酒五日巡礼 🚄",
                "category": "境外",
                "height": "tall"
            },
            {
                "id": 3,
                "image": "https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=400&h=250&fit=crop",
                "views": 104,
                "location": "荆州市",
                "title": "神农架秘境导览",
                "description": "华中屋脊·土家原乡·高山湿地·神农祭祀 🌲",
                "category": "景区",
                "height": "medium"
            }
        ]

    @classmethod
    def get_cards_by_category(cls, category: str) -> List[Dict[str, Any]]:
        """类方法：按分类获取卡片"""
        all_cards = cls.create_sample_cards()
        return [card for card in all_cards if card.get("category") == category]

    def clone_card(self, card: Dict[str, Any], deep: bool = False) -> Dict[str, Any]:
        """实例方法：深浅拷贝卡片"""
        if deep:
            return copy.deepcopy(card)
        else:
            return copy.copy(card)

# 创建路由器
api_router = APIRouter()

# 简化版API - 避免路由冲突问题
@api_router.get("/cards")
async def get_cards():
    """获取卡片列表 - 演示Python高级特性"""

    print("🔄 处理卡片数据...")

    # 创建示例数据
    all_cards = DataProcessor.create_sample_cards()
    print(f"✅ 创建了 {len(all_cards)} 个卡片")

    # 使用生成器处理数据
    processed_cards = list(DataProcessor.card_generator(all_cards))
    print(f"✅ 生成器处理了 {len(processed_cards)} 个卡片")

    # 使用迭代器过滤热门卡片
    hot_cards = list(DataProcessor.filter_cards_by_category(processed_cards, "热门"))
    print(f"✅ 迭代器过滤出 {len(hot_cards)} 个热门卡片")

    # 转换为响应格式
    card_responses = []
    for card in processed_cards[:3]:  # 只返回前3个
        card_response = CardResponse(
            id=card["id"],
            title=card["title"],
            description=card["description"],
            image=card["image"],
            location=card["location"],
            category=card["category"],
            type=card.get("type"),
            views=card["views"],
            height=card["height"]
        )
        card_responses.append(card_response)

    return {
        "message": "Python高级特性演示API",
        "cards": card_responses,
        "total": len(all_cards),
        "features_used": [
            "生成器(Generator) - 内存友好的数据处理",
            "迭代器(Iterator) - 惰性求值的数据遍历",
            "深浅拷贝 - 数据保护和性能优化",
            "静态方法(Static Methods) - 工具类方法"
        ]
    }

@api_router.get("/cards/demo")
async def demo_features():
    """Python高级特性演示"""

    # 演示深浅拷贝
    original_data = {"id": 1, "data": {"value": 100}}
    shallow_copy = copy.copy(original_data)
    deep_copy = copy.deepcopy(original_data)

    shallow_copy["data"]["value"] = 200  # 影响原始数据
    deep_copy["data"]["value"] = 300    # 不影响原始数据

    return {
        "message": "Python高级特性演示",
        "generator_demo": "使用生成器逐个处理数据",
        "iterator_demo": "使用迭代器过滤数据",
        "copy_demo": {
            "original_after_shallow": original_data["data"]["value"],  # 200 (受影响)
            "original_after_deep": original_data["data"]["value"],     # 200 (还是200，因为浅拷贝已修改)
            "shallow_copy": shallow_copy["data"]["value"],             # 200
            "deep_copy": deep_copy["data"]["value"]                    # 300
        },
        "static_methods": "使用静态方法创建和管理数据",
        "decorators": "使用装饰器增强功能"
    }

@api_router.get("/cards/features")
async def show_features():
    """展示Python高级特性"""

    # 演示静态方法
    sample_cards = DataProcessor.create_sample_cards()
    hot_cards = DataProcessor.get_cards_by_category("热门")

    return {
        "message": "Python 5大高级特性展示",
        "features": [
            "🧪 生成器 (Generator) - 内存友好的数据处理",
            "🔄 迭代器 (Iterator) - 惰性求值的数据遍历",
            "🎨 装饰器 (Decorator) - 功能增强和代码复用",
            "📋 深浅拷贝 - 数据保护和性能优化",
            "🔧 静态方法 (Static Methods) - 工具类方法"
        ],
        "total_sample_cards": len(sample_cards),
        "hot_cards_count": len(hot_cards),
        "example_cards": sample_cards[:2]
    }

# 将API路由添加到主应用
def include_api_routes(app):
    """包含API路由到主应用"""
    app.include_router(api_router, prefix="/api/v1", tags=["卡片API"])
    return app
